package com.pmt.feedplayer.ui

import androidx.compose.foundation.background
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.DpOffset
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage
import coil.request.ImageRequest
import com.pmt.feedplayer.core.logging.LogUtil
import com.pmt.feedplayer.data.VideoItem
import com.pmt.feedplayer.data.VideoListState
import com.pmt.feedplayer.processor.AndroidVideoProcessor
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.File
import java.util.concurrent.TimeUnit
import android.os.Environment

/**
 * Android平台的视频列表组件实现 - Material 3 风格
 */
@Composable
actual fun VideoFeed(
    videos: VideoListState,
    onVideoClick: (VideoItem) -> Unit,
    onLoadMore: () -> Unit
) {
    // 列表状态，用于检测滚动位置
    val listState = rememberLazyListState()
    
    // 是否已触发加载更多，避免重复加载
    var isLoadingMore by remember { mutableStateOf(false) }
    
    // 监听滚动事件，当滚动到底部时加载更多
    LaunchedEffect(listState) {
        snapshotFlow { listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index }
            .collect { lastVisibleIndex ->
                val totalItems = listState.layoutInfo.totalItemsCount
                // 当滚动到最后一个item时，触发加载更多
                if (lastVisibleIndex != null && 
                    lastVisibleIndex >= totalItems - 2 &&
                    !isLoadingMore && 
                    totalItems > 0) {
                    LogUtil.d("VideoFeed", "触发加载更多：lastVisibleIndex=$lastVisibleIndex, totalItems=$totalItems")
                    // 启动一个新的协程处理加载更多
                    launch {
                        isLoadingMore = true
                        try {
                            LogUtil.i("VideoFeed", "开始加载更多视频")
                            onLoadMore()
                            LogUtil.i("VideoFeed", "加载更多视频完成")
                        } catch (e: Exception) {
                            LogUtil.e("VideoFeed", "加载更多视频失败", e)
                        } finally {
                            // 无论成功失败，加载完成后都要重置状态
                            isLoadingMore = false
                            LogUtil.d("VideoFeed", "加载更多状态重置")
                        }
                    }
                }
            }
    }
    
    Column(modifier = Modifier.fillMaxSize()) {
        when (videos) {
            is VideoListState.Loading -> {
                Box(
                    modifier = Modifier.fillMaxSize(),
                    contentAlignment = Alignment.Center
                ) {
                    CircularProgressIndicator(modifier = Modifier.size(48.dp))
                }
            }
            is VideoListState.Error -> {
                Box(
                    modifier = Modifier.fillMaxSize(),
                    contentAlignment = Alignment.Center
                ) {
                    Column(horizontalAlignment = Alignment.CenterHorizontally) {
                        Text(text = "加载失败")
                        Text(text = videos.errorMessage, modifier = Modifier.padding(16.dp))
                        Button(onClick = onLoadMore) {
                            Text("重试")
                        }
                    }
                }
            }
            is VideoListState.Success -> {
                if (videos.data.isEmpty()) {
                    Box(
                        modifier = Modifier.fillMaxSize(),
                        contentAlignment = Alignment.Center
                    ) {
                        Column(horizontalAlignment = Alignment.CenterHorizontally) {
                            Text(text = "暂无视频")
                            Text(text = "未找到本地视频文件", modifier = Modifier.padding(top = 8.dp))
                        }
                    }
                } else {
                    LazyColumn(modifier = Modifier.fillMaxSize(), state = listState) {
                        items(videos.data) {
                            VideoItem(video = it, onClick = { onVideoClick(it) })
                        }
                        item {
                            // 加载更多指示器 - Material 3 风格
                            if (isLoadingMore) {
                                Box(
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .padding(16.dp),
                                    contentAlignment = Alignment.Center
                                ) {
                                    Row(
                                        modifier = Modifier
                                            .background(
                                                color = MaterialTheme.colorScheme.surfaceVariant,
                                                shape = MaterialTheme.shapes.medium
                                            )
                                            .padding(12.dp),
                                        verticalAlignment = Alignment.CenterVertically,
                                        horizontalArrangement = Arrangement.Center
                                    ) {
                                        CircularProgressIndicator(
                                            modifier = Modifier.size(20.dp),
                                            strokeWidth = 2.dp,
                                            color = MaterialTheme.colorScheme.primary
                                        )
                                        Text(
                                            text = "加载更多...",
                                            modifier = Modifier.padding(start = 12.dp),
                                            style = MaterialTheme.typography.bodyMedium,
                                            color = MaterialTheme.colorScheme.onSurfaceVariant
                                        )
                                    }
                                }
                            } else {
                                // 底部间距 - 确保列表底部有足够空间
                                Spacer(modifier = Modifier.height(64.dp))
                            }
                        }
                    }
                }
            }
        }
    }
}

@OptIn(ExperimentalFoundationApi::class)
@Composable
actual fun VideoItem(video: VideoItem, onClick: () -> Unit) {
    val context = LocalContext.current
    val videoProcessor = remember { AndroidVideoProcessor(context) }
    var showMenu by remember { mutableStateOf(false) }
    var menuPosition by remember { mutableStateOf<androidx.compose.ui.geometry.Offset?>(null) }
    var isProcessing by remember { mutableStateOf(false) }
    var processProgress by remember { mutableStateOf(0) }
    
    fun handleLongPress() {
        menuPosition = androidx.compose.ui.geometry.Offset(0f, 0f)
        showMenu = true
    }
    
    fun handleExtractVideoOnly() {
        showMenu = false
        isProcessing = true
        processProgress = 0
        
        val currentContext = context
        CoroutineScope(Dispatchers.IO).launch {
            try {
                val movieDir = currentContext.getExternalFilesDir(Environment.DIRECTORY_MOVIES)
                val videoFile = File(video.videoUrl)
                val outputVideoPath = File(movieDir, "no_audio_${videoFile.nameWithoutExtension}.mp4").absolutePath
                
                videoProcessor.extractVideoOnly(video.videoUrl, outputVideoPath).collect { progress ->
                    processProgress = progress
                }
                
                currentContext.toast("视频提取成功: $outputVideoPath")
            } catch (e: Exception) {
                currentContext.toast("处理失败: ${e.message}")
            } finally {
                isProcessing = false
            }
        }
    }
    
    fun handleExtractAudioOnly() {
        showMenu = false
        isProcessing = true
        processProgress = 0
        
        val currentContext = context
        CoroutineScope(Dispatchers.IO).launch {
            try {
                val musicDir = currentContext.getExternalFilesDir(Environment.DIRECTORY_MUSIC)
                val videoFile = File(video.videoUrl)
                val outputAudioPath = File(musicDir, "${videoFile.nameWithoutExtension}.aac").absolutePath
                
                videoProcessor.extractAudioOnly(video.videoUrl, outputAudioPath).collect { progress ->
                    processProgress = progress
                }
                
                currentContext.toast("音频提取成功: $outputAudioPath")
            } catch (e: Exception) {
                currentContext.toast("处理失败: ${e.message}")
            } finally {
                isProcessing = false
            }
        }
    }
    
    fun handleExtractBoth() {
        showMenu = false
        isProcessing = true
        processProgress = 0
        
        val currentContext = context
        CoroutineScope(Dispatchers.IO).launch {
            try {
                val movieDir = currentContext.getExternalFilesDir(Environment.DIRECTORY_MOVIES)
                val musicDir = currentContext.getExternalFilesDir(Environment.DIRECTORY_MUSIC)
                val videoFile = File(video.videoUrl)
                val outputVideoPath = File(movieDir, "no_audio_${videoFile.nameWithoutExtension}.mp4").absolutePath
                val outputAudioPath = File(musicDir, "${videoFile.nameWithoutExtension}.aac").absolutePath
                
                videoProcessor.extractAudioAndVideo(video.videoUrl, outputVideoPath, outputAudioPath).collect { progress ->
                    processProgress = progress
                }
                
                currentContext.toast("音视频已分离完成")
            } catch (e: Exception) {
                currentContext.toast("处理失败: ${e.message}")
            } finally {
                isProcessing = false
            }
        }
    }
    
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .padding(8.dp)
            .combinedClickable(
                onClick = onClick,
                onLongClick = { handleLongPress() }
            ),
        shape = MaterialTheme.shapes.medium,
        elevation = CardDefaults.cardElevation(defaultElevation = 4.dp)
    ) {
        Box(modifier = Modifier.fillMaxWidth()) {
            // 显示视频缩略图
            if (video.thumbnailUrl.isNotEmpty()) {
                AsyncImage(
                    model = ImageRequest.Builder(LocalContext.current)
                        .data(video.thumbnailUrl)
                        .crossfade(true)
                        .build(),
                    contentDescription = "Video thumbnail",
                    contentScale = ContentScale.Crop,
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(200.dp)
                )
            } else {
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(200.dp)
                        .background(Color.Gray)
                )
            }
            
            // 播放按钮
            Icon(
                imageVector = Icons.Default.PlayArrow,
                contentDescription = "播放",
                tint = Color.White,
                modifier = Modifier
                    .size(48.dp)
                    .align(Alignment.Center)
            )
            
            // 视频时长
            Box(
                modifier = Modifier
                    .align(Alignment.BottomEnd)
                    .padding(8.dp)
                    .background(Color.Black.copy(alpha = 0.7f))
                    .padding(4.dp)
            ) {
                Text(
                    text = formatDuration(video.duration),
                    color = Color.White,
                    style = MaterialTheme.typography.bodySmall
                )
            }
            
            // 处理进度指示器
            if (isProcessing) {
                Box(
                    modifier = Modifier
                        .fillMaxSize()
                        .background(Color.Black.copy(alpha = 0.5f))
                        .align(Alignment.Center)
                ) {
                    Column(
                        modifier = Modifier.align(Alignment.Center),
                        horizontalAlignment = Alignment.CenterHorizontally
                    ) {
                        CircularProgressIndicator(
                            progress = processProgress / 100f,
                            modifier = Modifier.size(64.dp)
                        )
                        Text(
                            text = "处理中: $processProgress%",
                            color = Color.White,
                            modifier = Modifier.padding(top = 8.dp)
                        )
                    }
                }
            }
        }
        
        // 视频信息
        Column(modifier = Modifier.padding(16.dp)) {
            Text(
                text = video.title,
                fontWeight = FontWeight.Bold,
                modifier = Modifier.padding(bottom = 8.dp),
                maxLines = 2,
                overflow = TextOverflow.Ellipsis
            )
            
            Row {
                Text(
                    text = video.authorName ?: "未知作者",
                    color = Color.Gray,
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis,
                    modifier = Modifier.weight(1f)
                )
                Text(
                    text = formatDuration(video.duration),
                    color = Color.Gray,
                    style = MaterialTheme.typography.bodySmall
                )
            }
        }
    }
    
    // 下拉菜单
    if (showMenu && menuPosition != null) {
        DropdownMenu(
            expanded = showMenu,
            onDismissRequest = { showMenu = false },
            offset = DpOffset(menuPosition!!.x.dp, menuPosition!!.y.dp)
        ) {
            DropdownMenuItem(
                text = { Text("仅提取视频") },
                onClick = { handleExtractVideoOnly() }
            )
            DropdownMenuItem(
                text = { Text("仅提取音频") },
                onClick = { handleExtractAudioOnly() }
            )
            DropdownMenuItem(
                text = { Text("音视频分离") },
                onClick = { handleExtractBoth() }
            )
        }
    }
}

/**
 * Context扩展函数，显示Toast消息
 */
fun android.content.Context.toast(message: String) {
    // 确保在UI线程显示Toast
    android.os.Handler(android.os.Looper.getMainLooper()).post {
        android.widget.Toast.makeText(this, message, android.widget.Toast.LENGTH_SHORT).show()
    }
}

/**
 * 格式化视频时长
 */
internal fun formatDuration(millis: Long): String {
    if (millis < 0) return "0:00"
    
    val totalSeconds = TimeUnit.MILLISECONDS.toSeconds(millis)
    val minutes = TimeUnit.SECONDS.toMinutes(totalSeconds)
    val seconds = totalSeconds % 60
    
    return if (minutes >= 60) {
        val hours = TimeUnit.MINUTES.toHours(minutes)
        val remainingMinutes = minutes % 60
        "%d:%02d:%02d".format(hours, remainingMinutes, seconds)
    } else {
        "%d:%02d".format(minutes, seconds)
    }
}